/*
 *  Copyright 2010 Alexey Frishman (alexey.frishman@gmail.com)
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not
 *  use this file except in compliance with the License. You may obtain a copy of
 *  the License at
 *  
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations under
 *  the License.
 * 
 */

package org.json4g.serialization.parameterized;

import static org.json4g.TypeUtil.fakeField;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

import org.json4g.serialization.AbstractJsonSerializer;
import org.json4g.serialization.JsonSerializer;
import org.json4g.serialization.policy.SerializationPolicy;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.gwtent.reflection.client.Field;
import com.gwtent.reflection.client.impl.ClassTypeImpl;

public class JsonMapSerializer extends AbstractJsonSerializer {

    private JsonSerializer itemSerializer;
    private SerializationPolicy policy;

    /**
     * 
     * @param itemSerializer
     *            serializer, which will be used handle items in the collection
     * @param policy
     *            serialization rules
     */
    public JsonMapSerializer(JsonSerializer itemSerializer, SerializationPolicy policy) {
        super(
                new ClassTypeImpl(Map.class),
                new ClassTypeImpl(HashMap.class),
                new ClassTypeImpl(LinkedHashMap.class),
                new ClassTypeImpl(TreeMap.class)
        );
        this.itemSerializer = itemSerializer;
        this.policy = policy;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Object deserialize(JSONValue json, Field field) {
        assertSupported(json, field.getType());
        ClassTypeImpl typeOfElements = (ClassTypeImpl) policy.getGenericTypeExtractor().extract(field);
        JSONObject jsonObject = json.isObject();
        Map map = createNewInstance(jsonObject.size());
        for (String key : jsonObject.keySet()) {
            map.put(key, itemSerializer.deserialize(jsonObject.get(key), fakeField(typeOfElements)));
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    @Override
    public JSONValue serialize(Object object) {
        assertSupported(object);
        Map<String, ?> map = (Map<String, ?>) object;
        JSONObject jsonMap = new JSONObject();
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            jsonMap.put(entry.getKey(), itemSerializer.serialize(entry.getValue()));
        }
        return jsonMap;
    }

    @Override
    protected boolean supports(JSONValue json) {
        return super.supports(json) && json.isObject() != null;
    }
    
    @SuppressWarnings("unchecked")
    protected Map createNewInstance(int size) {
        // TODO see comments to JsonSetSerializer.createNewInstance()
        return new LinkedHashMap(size);
    }

}
